package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.BaseDbTableProcess;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

/**
 * @author Felix
 * @date 2023/8/4
 * 过滤需要动态分流处理的事实表数据
 */
public class BaseDbTableProcessFunction extends BroadcastProcessFunction<JSONObject, String, JSONObject> {

    private Map<String, BaseDbTableProcess> configMap = new HashMap<>();

    private MapStateDescriptor<String, BaseDbTableProcess> mapStateDescriptor;

    public BaseDbTableProcessFunction(MapStateDescriptor<String, BaseDbTableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //将配置表中的配置信息预加载到程序中
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall0222_config?" +
            "user=root&password=123456&useUnicode=true&" +
            "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");

        String sql = "select * from gmall0222_config.table_process_dwd";
        //获取数据库操作对象
        PreparedStatement ps = conn.prepareStatement(sql);
        //执行SQL语句
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        //处理结果集
        while (rs.next()) {
            //定义一个json对象，用于封装遍历出来一条结果
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName, columnValue);
            }
            //利用fastJson将jsonObj转换为实体类对象
            BaseDbTableProcess tableProcess = JSON.toJavaObject(jsonObj, BaseDbTableProcess.class);
            String sourceTable = tableProcess.getSourceTable();
            String sourceType = tableProcess.getSourceType();
            String key = sourceTable + ":" + sourceType;
            configMap.put(key, tableProcess);
        }
        //释放资源
        rs.close();
        ps.close();
        conn.close();
    }

    //处理主流数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        //获取操作业务数据库表表名
        String table = jsonObj.getString("table");
        //获取操作类型
        String type = jsonObj.getString("type");
        //拼接key
        String key = table + ":" + type;
        //获取广播状态
        ReadOnlyBroadcastState<String, BaseDbTableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        BaseDbTableProcess tableProcess = null;

        if((tableProcess = broadcastState.get(key)) != null
            ||(tableProcess = configMap.get(key)) != null){
            //如果获取到的配置信息不为空，说明当前处理的数据是需要动态分流的事实表数据

            //获取到data部分内容，传递到下游
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");
            //在向下游传递数据前，过滤掉不需要传递的属性
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj,sinkColumns);
            //在向下游传递数据前，补充输出的目的地主题
            String sinkTable = tableProcess.getSinkTable();
            dataJsonObj.put("sink_table",sinkTable);
            //在向下游传递数据前，补充处理的事件时间属性
            dataJsonObj.put("ts",jsonObj.getLong("ts"));

            out.collect(dataJsonObj);
        }
    }

    //过滤掉不需要传递的属性
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        //获取要保留的属性
        String[] fieldArr = sinkColumns.split(",");
        List<String> fieldList = Arrays.asList(fieldArr);
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!fieldList.contains(entry.getKey()));
    }

    //处理广播流数据
    @Override
    public void processBroadcastElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
        //"op":"r": {"before":null,"after":{"source_table":"favor_info","source_type":"insert","sink_table":"dwd_interaction_favor_add","sink_columns":"id,user_id,sku_id,create_time"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0222_config","sequence":null,"table":"table_process_dwd","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1691129684797,"transaction":null}
        //"op":"c": {"before":null,"after":{"source_table":"aa","source_type":"insert","sink_table":"dwd_a","sink_columns":"id,name"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1691129756000,"snapshot":"false","db":"gmall0222_config","sequence":null,"table":"table_process_dwd","server_id":1,"gtid":null,"file":"mysql-bin.000008","pos":11391388,"row":0,"thread":null,"query":null},"op":"c","ts_ms":1691129756850,"transaction":null}
        //"op":"u": {"before":{"source_table":"aa","source_type":"insert","sink_table":"dwd_a","sink_columns":"id,name"},"after":{"source_table":"aa","source_type":"insert","sink_table":"dwd_a","sink_columns":"id,name,age"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1691129804000,"snapshot":"false","db":"gmall0222_config","sequence":null,"table":"table_process_dwd","server_id":1,"gtid":null,"file":"mysql-bin.000008","pos":11391744,"row":0,"thread":null,"query":null},"op":"u","ts_ms":1691129804197,"transaction":null}
        //"op":"d": {"before":{"source_table":"aa","source_type":"insert","sink_table":"dwd_a","sink_columns":"id,name,age"},"after":null,"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1691129840000,"snapshot":"false","db":"gmall0222_config","sequence":null,"table":"table_process_dwd","server_id":1,"gtid":null,"file":"mysql-bin.000008","pos":11392125,"row":0,"thread":null,"query":null},"op":"d","ts_ms":1691129840269,"transaction":null}
        // System.out.println(jsonStr);
        //为了处理方便  先将jsonStr转换为jsonObj
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        //根据当前jsonObj获取对配置表进行的操作类型
        String op = jsonObj.getString("op");
        //获取广播状态
        BroadcastState<String, BaseDbTableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);

        if("d".equals(op)){
            //如果从配置表中删除了数据，那么应该从广播状态以及configMap中删除掉对应配置
            BaseDbTableProcess before = jsonObj.getObject("before", BaseDbTableProcess.class);
            String sourceTable = before.getSourceTable();
            String sourceType = before.getSourceType();
            String key = sourceTable + ":" + sourceType;
            broadcastState.remove(key);
            configMap.remove(key);
        }else{
            //如果对配置表做了删除外的其它操作，那么应该将对应的配置信息put到广播状态以及configMap中
            BaseDbTableProcess after = jsonObj.getObject("after", BaseDbTableProcess.class);
            String sourceTable = after.getSourceTable();
            String sourceType = after.getSourceType();
            String key = sourceTable + ":" + sourceType;
            broadcastState.put(key,after);
            configMap.put(key,after);
        }
    }
}
